import React, { createContext, useContext, useEffect } from "react";
import { IntlProvider } from "react-intl";
import { useAppContext } from "./Provider";
import { useMemo, useState } from "react";
import { utils } from "elmer-common";
import lodash from "lodash";

const I18nContext = createContext({
    locale: "zh-CN",
    messages: {}
});

export const I18nProvider = ({ children }: any) => {
    const appContext = useAppContext();
    
    const [ cacheMessages, setCacheMessages ] = useState<any>(() => {
        const defaultData = localStorage.getItem("i18n");
        return defaultData && !utils.isEmpty(defaultData) ? JSON.parse(defaultData) : {};
    });
    const [ locale, setLocale ] = useState<string>(() => {
        const localeFromSession = sessionStorage.getItem("locale");
        if (localeFromSession && !utils.isEmpty(localeFromSession)) {
            return localeFromSession;
        } else {
            return appContext.config.locale ?? navigator.language ?? "zh-CN";
        }
    });
    const [ defaultLocale ] = useState(navigator.language ?? "zh-CN");
    const currentMessage = useMemo(() => {
        const hardcodeMessages = appContext.config.i18n[locale] ?? appContext.config.i18n[defaultLocale];
        const cacheMessageData = cacheMessages[locale] || {};
       
        return {
            ...hardcodeMessages,
            ...cacheMessageData
        };
    }, [locale, defaultLocale, appContext.config.i18n, cacheMessages]);
    const i18nContext = useMemo(() => {
        return {
            messages: currentMessage,
            locale,
            switchLocale: (newLocale: string) => {
                sessionStorage.setItem("locale", newLocale);
                setLocale(newLocale);
            },
            updateMessages: (newMessages: any) => {
                const updateData = lodash.merge(cacheMessages, newMessages);
                setCacheMessages(JSON.parse(JSON.stringify(updateData)));
            }
        }
    }, [currentMessage, locale, cacheMessages]);
    useEffect(() => {
        if(!appContext.config.i18n[defaultLocale]) {
            console.error(`[配置错误] 默认语言(${defaultLocale}),未找到对应配置数据。`);
        }
    }, [appContext.config.i18n, defaultLocale]);

    return (
        <I18nContext.Provider value={i18nContext}>
            <IntlProvider
                locale={locale}
                messages={currentMessage}
                defaultLocale={defaultLocale}
            >
                {children}
            </IntlProvider>
        </I18nContext.Provider>
    );
};

export const useI18n = () => useContext(I18nContext);
